// src/errors/errorHandler.ts
import { FastifyError, FastifyInstance } from 'fastify';
import { ApiResponse } from '../common/response';


export default (fastify: FastifyInstance) => {
  fastify.setErrorHandler((error: FastifyError, _, reply) => {
    // 处理 Zod 验证错误
    if (error.validation) {
      return ApiResponse.error(reply, `参数错误: ${error.message}`, 400);
    }

    // 处理自定义错误
    if (error instanceof AppError) {
      return ApiResponse.error(reply, error.message, error.statusCode);
    }

    // 其他错误
    fastify.log.error(`${error.message}`);
    ApiResponse.error(reply, 'Internal Server Error');
  });
};